package com.third.device.mg.serialport.help.netty

import com.third.device.mg.serialport.MGSerialPort
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.utils.SLog
import com.third.device.mg.serialport.utils.mainThread
import com.third.device.mg.serialport.utils.toHexString
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/31
 * Description:通用handler，处理I/O时间
 * [ChannelHandler.Sharable]客户端线程安全
 * [SimpleChannelInboundHandler]客户端处理类
 * [ByteBuf]指定客户端消息包格式为字节
 */
@ChannelHandler.Sharable
class ReadHandler(private val ip :String, val port:Int) : SimpleChannelInboundHandler<ByteArray>() {
    var listener: MGNettyConnectListener? = null
    companion object{
        private const val TAG = "${MGSerialPort.BASE_TAG}:ReadHandler:"
    }
    override fun channelRead0(ctx: ChannelHandlerContext?, msg: ByteArray?) {
        msg?.mainThread {
            SLog.d(TAG,"Read : $ip:$port ==> ${this.toHexString()}")
            listener?.readBack(ip ,port ,this)
        }
    }
    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        SLog.d(TAG,"Read : $ip:$port ==> exceptionCaught")
       /* cause?.mainThread {
            this.printStackTrace()
            listener?.errorBack(ip ,port ,this)
            listener?.disconnectBack(ip ,port)
        }*/
    }

}